﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using System.Text;
using Facebook;
using Microsoft.Xna.Framework;


namespace Hangout.Client.Accounts
{
    public partial class Facebook : PhoneApplicationPage
    {

        

        private const string ExtendedPermissions = "user_about_me,publish_stream,user_checkins,friends_checkins,user_likes,user_location,email,user_relationships,user_relationship_details,read_friendlists,publish_checkins,offline_access";
        private readonly FacebookClient _fb = new FacebookClient();
        

        public Facebook()
        {
            InitializeComponent();
        }

        

        

        private void PhoneApplicationPage_Loaded(object sender, RoutedEventArgs e)
        {

            try
            {
                var parameters = new Dictionary<string, object>();
                parameters["client_id"] = AppID.FacebookAppID;
                parameters["redirect_uri"] = "https://www.facebook.com/connect/login_success.html";
                parameters["response_type"] = "token";
                parameters["display"] = "touch";
                parameters["scope"] = ExtendedPermissions;
                FacebookAuthenticationBrowser.Navigate(_fb.GetLoginUrl(parameters));
            }
            catch (Exception ex)
            {
                Core.Exceptions.ExceptionReporting.Report(ex);
                MessageBox.Show(ErrorText.GenericErrorText, ErrorText.GenericErrorCaption, MessageBoxButton.OK);
            }

        }




        
        private void Browser_Navigated(object sender, System.Windows.Navigation.NavigationEventArgs e)
        {
            try
            {

                if (e.Uri.ToString().Contains(@"m.facebook.com/login.php?app_id=" + AppID.FacebookAppID))
                {
                    PB.Visibility = System.Windows.Visibility.Collapsed;
                    ShowBrowser.Begin();
                }

                FacebookOAuthResult oauthResult;
                if (!_fb.TryParseOAuthCallbackUrl(e.Uri, out oauthResult))
                {
                    return;
                }

                if (oauthResult.IsSuccess)
                {
                    HideBrowser.Begin();

                    if (MessageBoxResult.OK == MessageBox.Show(Messages.PrivacyPolicyText, Messages.PrivacyPolicyCaption, MessageBoxButton.OKCancel))
                    {

                        PB.Visibility = System.Windows.Visibility.Visible;

                        var accessToken = oauthResult.AccessToken;

                        Settings.Settings.FacebookAccessToken = accessToken;
                        Settings.Settings.FacebookAccessTokenExpires = oauthResult.Expires;
                        //load all the user profile information and store.

                        RegisterUser();
                    }
                    else
                    {
                        new Game().Exit();
                    }


                }
                else
                {
                    MessageBox.Show(oauthResult.ErrorDescription);
                }
            }
            catch (Exception ex)
            {
                Core.Exceptions.ExceptionReporting.Report(ex);
                MessageBox.Show(ErrorText.GenericErrorText, ErrorText.GenericErrorCaption, MessageBoxButton.OK);
            }
        }

        private void RegisterUser()
        {
            try
            {

                
                Services.AccountServiceClient.RegisterUserCompleted += new EventHandler<AccountService.RegisterUserCompletedEventArgs>(client_RegisterUserCompleted);
                Services.AccountServiceClient.RegisterUserAsync(Settings.Settings.FacebookAccessToken);
            }
            catch (Exception ex)
            {
                Core.Exceptions.ExceptionReporting.Report(ex);
                MessageBox.Show(ErrorText.GenericErrorText, ErrorText.GenericErrorCaption, MessageBoxButton.OK);
            }
        }

       

        void client_RegisterUserCompleted(object sender, AccountService.RegisterUserCompletedEventArgs e)
        {

            Services.AccountServiceClient.RegisterUserCompleted -= new EventHandler<AccountService.RegisterUserCompletedEventArgs>(client_RegisterUserCompleted);
            try
            {
                if (e.Error == null)
                {
                    if (e.Result != null)
                    {
                        Settings.Settings.UserData = e.Result;
                        Settings.Settings.UserID = e.Result.UserID;
                        Settings.Settings.FacebookUserID = (long)e.Result.FacebookUserID;
                        Settings.Settings.FacebookUserFullName = e.Result.Name;

                       
                    }
                    else
                    {
                        Dispatcher.BeginInvoke(() =>
                           {
                               MessageBox.Show("We had an error signing up. We'll be back shortly.", "We're down", MessageBoxButton.OK);
                           });

                        NavigateToAccounts();

                        return;
                    }

                }
                else
                {
                    Dispatcher.BeginInvoke(() =>
                            {
                                MessageBox.Show("We had an error signing up. We'll be back shortly.", "We're down", MessageBoxButton.OK);
                            });

                    

                    Core.Exceptions.ExceptionReporting.Report(e.Error);
                    MessageBox.Show(e.Error.Message);

                    NavigateToAccounts();
                    return;
                }


                NavigateToProfile();
            }
            catch (Exception ex)
            {
                Core.Exceptions.ExceptionReporting.Report(ex);
                MessageBox.Show(ErrorText.GenericErrorText, ErrorText.GenericErrorCaption, MessageBoxButton.OK);
            }
        }

        private void NavigateToAccounts()
        {
            try
            {
                Dispatcher.BeginInvoke(() =>
                {
                    NavigationService.Navigate(new Uri(Navigation.Accounts, UriKind.RelativeOrAbsolute));
                });
            }
            catch (Exception ex)
            {
                Core.Exceptions.ExceptionReporting.Report(ex);
                MessageBox.Show(ErrorText.GenericErrorText, ErrorText.GenericErrorCaption, MessageBoxButton.OK);
            }
        }

        private void NavigateToProfile()
        {
            try
            {
                Dispatcher.BeginInvoke(() =>
                            {
                                NavigationService.Navigate(new Uri(Navigation.Profile, UriKind.RelativeOrAbsolute));
                            });
            }
            catch (Exception ex)
            {
                Core.Exceptions.ExceptionReporting.Report(ex);
                MessageBox.Show(ErrorText.GenericErrorText, ErrorText.GenericErrorCaption, MessageBoxButton.OK);
            }
            
        }

        

        


        

    }
}